/* $Id: SessionsModel.java 129 2011-08-26 05:27:43Z altdotua@gmail.com $ */

package alt.djudge.frontend.server.models;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import org.hibernate.criterion.Order;

import alt.djudge.frontend.server.Deployment;
import alt.djudge.frontend.server.datatypes.SessionEntry;


public class SessionsModel
{
	private static CoreInterface<SessionEntry> core = Deployment.isGAE() ?  
		new AbstractBigtableModelCore<SessionEntry>()
		{
			@Override
			protected Order getOrdering()
			{
				return Order.asc("id");
			}
			
			@Override
			protected Class<SessionEntry> getEntryClass()
			{
				return SessionEntry.class;
			}
		}
	:
		new AbstractDBModelCore<SessionEntry>()
		{
			@Override
			protected Order getOrdering()
			{
				return Order.asc("id");
			}
			
			@Override
			protected Class<SessionEntry> getEntryClass()
			{
				return SessionEntry.class;
			}
		};
		
	public static List<SessionEntry> getAllEntries()
	{
		return core.getAllEntries();
	}
	
	public static List<SessionEntry> getEntries(Map<String, Object> map)
	{
		return core.getEntries(map);
	}
	
	public static String generateAuthToken()
	{
		StringBuffer sb = new StringBuffer();
		Random random = new Random(new Date().getTime());
		for (int i = 0; i < 64; i++)
		{
			char c = (char) (random.nextInt(26) + 'a');
			sb.append(c);
		}
		return sb.toString();
	}
	
	public static CoreInterface<SessionEntry> getCore()
	{
		return core.getAdapter();
	}

	public static void deleteUserSessions(Long userId)
	{
		Map<String, Object> sessReq = new HashMap<String, Object>();
		sessReq.put("userId", userId);
		List<SessionEntry> list = getEntries(sessReq);
		for (SessionEntry entry: list)
			entry.delete();
	}
}
